<template>
	<div class="system-dept-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="deptDialogFormRef" :model="state.ruleForm" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="上级部门">
							<el-cascader :options="state.deptData"
								:props="{ checkStrictly: true, value: 'id', label: 'name' }" placeholder="请选择部门" clearable
								class="w100" v-model="state.deptLevel">
								<template #default="{ node, data }">
									<span>{{ data.name }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="部门名称">
							<el-input v-model="state.ruleForm.name" placeholder="请输入部门名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="负责人">
							<el-select v-model="state.ruleForm.leader_id" placeholder="请输入负责人" clearable filterable remote
								reserve-keyword :remote-method="getUser" :loading="state.remote.loading">
								<el-option v-for="item in state.remote.options" :key="item.id" :label="item.username"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="部门状态">
							<el-switch v-model="state.ruleForm.status" inline-prompt :active-value="1" active-text="启"
								:inactive-value="0" inactive-text="禁"></el-switch>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="部门描述">
							<el-input v-model="state.ruleForm.description" type="textarea" placeholder="请输入部门描述"
								maxlength="150"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemDeptDialog">
import { reactive, ref } from 'vue';
import { useUserApi } from '/@/api/user';
import { useDeptApi } from '/@/api/dept';
import { ElMessage } from 'element-plus';

const userApi = useUserApi();
const deptApi = useDeptApi();
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const deptDialogFormRef = ref();
const state = reactive({
	ruleForm: {
		id: 0,
		fid: 0,
		name: '', // 部门名称
		leader_id: null as unknown as number, // 负责人
		status: 1, // 部门状态
		description: '', // 部门描述
	},
	deptLevel: [] as number[], // 上级部门
	deptData: [] as DeptTreeType[], // 部门数据
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	// 搜索用户参数
	params: {
		page: 1,
		pageSize: 5,
		username: ""
	},
	remote: {
		remoteMethod: "",
		loading: false,
		options: [] as RowUserType[]
	}
});

// 打开弹窗
const openDialog = async (type: string, row: RowDeptType) => {
	state.dialog.type = type;
	if (type === 'edit') {
		state.ruleForm = { ...row } as RowDeptType;
		await getUpperDept(row.id,'edit')
		if (state.deptLevel.length > 0) state.deptLevel.pop();
		state.dialog.title = '修改部门';
		state.dialog.submitTxt = '修 改';
	} else {
		state.ruleForm = { status: 1 } as RowDeptType;
		if (row) {
			await getUpperDept(row.id,'add')
			state.ruleForm.fid = row.id;
		}
		state.dialog.title = '新增部门';
		state.dialog.submitTxt = '新 增';
	}
	state.dialog.isShowDialog = true;
	getMenuData();
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
	state.ruleForm.fid = state.deptLevel[state.deptLevel.length - 1];
	if (state.dialog.type === 'add') {
		 addDept().then(res => {
			ElMessage.success("新增成功");
			closeDialog();
			emit('refresh');
		}).catch(err => {
			ElMessage.warning("新增失败");
		});
	} else {
		 updateDept().then(res => {
			ElMessage.success("修改成功");
			closeDialog();
			emit('refresh');
		}).catch(err => {
			ElMessage.warning("修改失败");
		});
	}
};
// 初始化部门数据
const getMenuData =  () => {
	 deptApi.getAllDepts().then(res => {
		state.deptData = [...res.result];
	})
};

// 搜索用户
const getUser =  (query: string) => {
	state.params.username = query;
	 userApi.getUserNoRole(state.params).then(res => {
		state.remote.options = [...res.result];
	})
}
// 获取所有上级部门
const getUpperDept = (id: number,type:string) => {
	deptApi.getUpper(id).then(res => {
		let result = res.result
		if(result.length!==0 && type === 'edit'){
			result.pop()
		}
		// 让部门fid=id
		state.ruleForm.fid = id;
		// 让上级部门数组等于这些
		state.deptLevel = [];
		result.map((v: any) => {
			state.deptLevel.push(v.id);
		});
	})
}
// 请求新增部门接口
const addDept = async () => {
	state.ruleForm.id = 0;
	return await deptApi.addDept(state.ruleForm)
}
// 请求修改部门接口
const updateDept = async () => {
	return await deptApi.updateDept(state.ruleForm)
}
// 暴露变量
defineExpose({
	openDialog,
});
</script>
